#ifndef _COMMIN_HPP_
#define _COMMIN_HPP_

#include <iostream>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define PATHNAME "."
#define PROJ_ID 0x11
#define MAX_SIZE 4096


key_t getKey()
{
    key_t ret = ftok(PATHNAME, PROJ_ID);
    if (ret < 0)
    {
        std::cerr << "getKey : " << errno << " : " << strerror(errno) << std::endl;
        exit(errno);
    }
    return ret;
}

int getShmHelper(key_t key, int flags)
{
    int shmid = shmget(key, MAX_SIZE, flags);
    if (shmid < 0)
    {
        std::cerr << "getShmHelper : " << errno << " : " << strerror(errno) << std::endl;
        exit(errno);
    }
    return shmid;
}

int getShm(key_t key)
{
    return getShmHelper(key, IPC_CREAT);
}

int createShm(key_t key)
{
    return getShmHelper(key, IPC_CREAT | IPC_EXCL | 0600);
}

void delShm(int shmid)
{
    if (shmctl(shmid, IPC_RMID, nullptr) == -1)
    {
        std::cerr << "delShm : " << errno << " : " << strerror(errno) << std::endl;
        exit(errno);
    }
}


void* attchShm(int shmid)
{
    void *mem = shmat(shmid, nullptr, 0);
    if ((long long)mem == -1L)
    {
        std::cerr << "attchShm : " << errno << " : " << strerror(errno) << std::endl;
        exit(errno);
    }
    return mem;
}

void deattchShm(void* addr)
{
    if (shmdt(addr) < 0)
    {
        std::cerr << "deattchShm : " << errno << " : " << strerror(errno) << std::endl;
        exit(errno);
    }
}

#endif